package cn.com.dashihui.api.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Duang;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.weixin.sdk.utils.JsonUtils;

import cn.com.dashihui.api.base.BaseController;
import cn.com.dashihui.api.common.OrderCode;
import cn.com.dashihui.api.common.ResultMap;
import cn.com.dashihui.api.common.SysConfig;
import cn.com.dashihui.api.dao.Order;
import cn.com.dashihui.api.dao.OrderE;
import cn.com.dashihui.api.dao.OrderG;
import cn.com.dashihui.api.dao.OrderPayAPIRecord;
import cn.com.dashihui.api.dao.User;
import cn.com.dashihui.api.interceptor.AuthLoginInterceptor;
import cn.com.dashihui.api.service.GoodsService;
import cn.com.dashihui.api.service.GroupbuyingService;
import cn.com.dashihui.kit.CommonKit;
import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.DoubleKit;
import cn.com.dashihui.pay.ZY.EncryUtils;
import cn.com.dashihui.pay.wx.kit.HttpsRequest;
import cn.com.dashihui.pay.wx.kit.UtilKit;
import cn.com.dashihui.pay.wx.request.RefOrderReqData;
import cn.com.dashihui.pay.wx.response.RefOrderResData;

/**
 * ***********************************************
　 * <p>类名: GroupbuyingController</p> 
　 * <p>描述: 团购订单的生成</p> 
　 * @author niufc 
　 * @date 2019年8月20日 
  * ************************************************
 */
@Before(AuthLoginInterceptor.class)
public class GroupbuyingController extends BaseController{
	
	//使用Duang.duang进行封装，使普通类具有事务的功能
	private GroupbuyingService service = Duang.duang(GroupbuyingService.class);
	//使用Duang.duang进行封装，使普通类具有事务的功能
	private GoodsService goodsservice = Duang.duang(GoodsService.class);
	
	@Clear
	public void Demo(){
		service.demo();
		renderSuccess("成功");
	}
	
	/**
	 * 商品详情
	 * @param GOODSID 商品ID
	 */
	@Clear(AuthLoginInterceptor.class)
	public void detail(){
		String goodsidStr = getPara("GOODSID");
		String isSpike = getPara("SPIKE");
		int isLook = getParaToInt("ISLOOK",0);
		if(StrKit.isBlank(isSpike)){
			isSpike = "0";
		}
		if(StrKit.isBlank(goodsidStr)){
			renderFailed("参数GOODSID不能为空");
			return;
		}else{
			//是商品详情页
//			if(isLook==1){
//				if(service.updateLookByid(goodsidStr)!=1){
//					renderFailed("更新浏览量失败");
//				}
//			}
			//查询商品详情信息
			Record goods;
			if(getCurrentUser()!=null){
				//如果当前有用户登录，则查询商品详情的同时，查询该用户与该商品的收藏关系
				goods = service.findDetail(getCurrentUser().getInt("id"), Integer.valueOf(goodsidStr));
			}else{
				//如果当前没有用户登录，则只查询商品详情
				goods = service.findDetail(Integer.valueOf(goodsidStr));
			}
			if(goods!=null){
				//查询商品的图片集，并遍历拼成数组形式，如：["/goods/xxx1.jpg","goods/xxx2.jpg"]
				List<Record> images = goodsservice.findImages(goods.getStr("LUNBONUM"));
				List<String> strList = new ArrayList<String>();
				if(images!=null&&images.size()!=0){
					for(Record image : images){
						strList.add(image.getStr("THUMB"));
					}
				}
				//查询商品的普遍规格集，并便利拼成数组形式
				List<Record> items = goodsservice.findComSpec(Integer.valueOf(goodsidStr));
				if(items!=null&&items.size()!=0){
					goods.set("Comspec", items);
				}
				//邮费
				Double postAge = 0.00;
				Double postAgeFree = 0.00;
				try {
					postAge = SysConfig.getPostAge();
					postAgeFree = SysConfig.getPostAgeFree();
				} catch (Exception e) {
					renderFailed("查询邮费失败");
					return;
				}
				goods.set("postAge", postAge);
				goods.set("postAgeFree", postAgeFree);
				//设置给商品详情信息
				goods.set("IMAGES", strList);
				renderSuccess(goods);
			}else{
	    		renderFailed("商品不存在");
			}
		}
	}
	/**
	 *   检查开团是否需要下单
	 */
	public void check(){
		String goodIds = getPara("GOODSID");
		if(StrKit.isBlank(goodIds)){
			renderFailed("参数GOODSID不能为空");
    		return;
		}
		int check = service.check(getCurrentUser(),goodIds);
		if ( check==1 ){
			renderSuccess(ResultMap.newInstance().put("CHECK", "ISCHECK"));
		} else {
			renderSuccess(ResultMap.newInstance().put("CHECK", "NOCHECK"));
		}
	}
	
	/**
	 * 生成订单
	 */
	public void save(){
		String goodIds = getPara("GOODSID");
		String amoun = getPara("AMOUNT");	//购买金额
		String tel = getPara("TEL");		//联系人电话
		String address = getPara("ADDRESSID");	//联系人地址
		String describe = getPara("DESCRIBE");	//联系人备注
		String zsactivity = getPara("ZSACTIVITY");	//是否赠送
		String zscouponnum = getPara("ZSCOUPONNUM"); //赠送优惠券
		String zsdedunum = getPara("ZSDEDUNUM");	//赠送抵扣券
		String zspointnum = getPara("ZSPOINTNUM");	//赠送积分
		String isRedeem = getPara("ISREDEEM");	//类型    0单独购买  1发起拼单(首单开团，普通拼团) 2开团中团  3参与团中团 
		String teamNum = getPara("TEAMNUM");	//团中团编号
		
		if(StrKit.isBlank(goodIds)){
			renderFailed("参数STOREID不能为空");
    		return;
		}else if(StrKit.isBlank(address)){
			renderFailed("参数ADDRESS不能为空");
    		return;
		}else if(StrKit.isBlank(amoun)){
			renderFailed("参数AMOUNT不能为空");
    		return;
		}else if(StrKit.isBlank(isRedeem)){
			renderFailed("参数ISREDEEM不能为空");
    		return;
		}else if(StrKit.isBlank(tel)){
			renderFailed("参数TEL不能为空");
    		return;
		}else if(StrKit.isBlank(zsactivity)){
			renderFailed("参数ZSACTIVITY不能为空");
    		return;
		}else if(!StrKit.isBlank(describe)&&describe.length()>=200){
			renderFailed("参数DESCRIBE内容过长");
    		return;
		}
		Double amount = Double.parseDouble(amoun);
		//团购订单的订单编号，以大写字母T开头
		String orderNum = "T"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
		
		Record add = Db.findById("t_bus_user_address", address);
		if(add == null){
			renderFailed("地址有误");
			return;
		}
		OrderG order = new OrderG()
				.set("orderNum", orderNum)
				.set("userid", getCurrentUser().getInt("id"))
				.set("countnum", 1)
				.set("amount", amount)
				.set("payState", OrderCode.OrderPayState.NO_PAY)
				.set("goodsid", goodIds)
				.set("orderState", OrderCode.OrderState.NORMAL)
				.set("tel", tel)
				.set("addressid", address)
				.set("receivename", add.get("linkname"))
				.set("receiveaddress", add.get("address"))
				.set("startDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
				.set("expireDate",  DatetimeKit.getIntervalFormatDate(PropKit.getInt("constants.order.interval"), "yyyy-MM-dd HH:mm:ss"));
		if("3".equals(isRedeem)){
			if(StrKit.isBlank(teamNum)){
				renderFailed("参数TEAMNUM不能为空");
	    		return;
			}else{
				order.set("teamNum", teamNum);
			}
		}
		if(zsactivity.equals("2")){
			if(!StrKit.isBlank(zscouponnum)){
				order.set("jypoint",zscouponnum);//赠送优惠券
			}
			if(!StrKit.isBlank(zsdedunum)){
				order.set("jkpoint",zsdedunum);//赠送抵扣券
			}
			if(!StrKit.isBlank(zspointnum)){
				order.set("sppoint",zspointnum);//赠送积分
			}
		}
		//用户如填写了备注，则记录
		if(StrKit.notBlank(describe)){
			order.set("describe", describe);
		}
		try {
			int count = service.save(order,isRedeem,getCurrentUser());
			if(count == 0){
				Record re = new Record();
				re.set("orderNum", orderNum);
				renderSuccess(re);
			}else if(count == 4){
				renderFailed("无开团资格");
			}else if(count == 5){
				renderFailed("团长订单未支付,违规操作");
			}else if(count == 7){
				renderFailed("当天购买次数达到最大值，请改日再来");
			}else if(count == 8){
				renderFailed("该团购已经结束");
			}else if(count == 9){
				renderFailed("该团购地址有误");
			}else{
				logger.info(">>>>>>>>>>>>>>"+count);
				renderFailed("系统异常，请稍后再试");
			}
		} catch (Exception e) {
			e.printStackTrace();
			renderFailed("系统异常，请稍后再试");
			return;
		}
	}
	
	/**
	 * 团购预支付
	 * FLAG  支付方式   1 微信  5 郑大余额 6余额支付
	 * TOKENP   5郑大支付需要
	 * ORDERNUM  订单号
	 */
	public void pay(){
		String orderNum = getPara("ORDERNUM");
		String flagStr = getPara("FLAG");
		String token=getPara("TOKENP");
		if("5".equals(flagStr)){
			if(StrKit.isBlank(token)){
				renderFailed("参数TOKENP不能为空");
	    		return;
			}
		}
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else if("0".equals(flagStr)){
			renderFailed("请选择支付方式");
    		return;
		}
		//获取客户端IP
		String remoteip = EncryUtils.getRealIp(getRequest());
		//判断是否PC端
		String isPC = EncryUtils.JudgeIsMoblie(getRequest());
		try {
			String url = service.pay(orderNum,flagStr,token,getCurrentUser(),remoteip,isPC);
			if(flagStr.equals("1")){
				Record re = new Record().set("url", url);
				renderSuccess(re);
				return;
			}else if (flagStr.equals("3")) {
				renderSuccess(ResultMap.newInstance().put("URL", url).getAttrs());
				return;
			}else if (flagStr.equals("6")) {
				if ("SUCCESS".equals(url)) {
					renderSuccess("支付成功");
					return;
				}else {
					renderFailed("支付失败");
					return;
				}
			}else{
				renderSuccess(url);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			String split = e.getMessage().split(":")[1];
			renderFailed(split);
		}
	}
	/**
	 * 团购预支付微信小程序端
	 * ORDERNUM  订单号
	 */
	public void pay1(){
		//获取订单支付方式
				String flag=getPara("FLAG");
		//获取OPENID
		String openid=getPara("OPENID");
		if(StrKit.isBlank(openid)){
			renderFailed("参数OPENID不能为空");
    		return;
		}
		//获取订单号
		String orderNum = getPara("ORDERNUM");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}
		//获取配置项
		String appid =PropKit.get("MPWXPAY.appid");
		String mch_id =PropKit.get("MPWXPAY.mch_id");
		String paternerKey =PropKit.get("MPWXPAY.paternerkey");
		String notify_url =PropKit.get("MPWXPAY.goodsOrderNotifyUrl");
		//获取客户端IP
		String remoteip = EncryUtils.getRealIp(getRequest());
		//查询订单是否存在
		OrderG order = OrderG.me().findFirst("SELECT * FROM t_bus_order_gb WHERE orderNum = ? AND payState=? ", orderNum,OrderCode.OrderPayState.NO_PAY);
		if(order==null){
			renderFailed("订单不存在");
    		return;
		}
		//验证订单是否有效
		if(DatetimeKit.compareDate(order.getDate("expireDate")) == -1){
			renderFailed("您的订单已过期");
			return;
		}
		//验证团购是否过期
		Date date = order.getDate("gbendtime");
		if (DatetimeKit.compareDate(date)<0 || DatetimeKit.compareDate(date)==0 ) {
			renderFailed("团购已过期");
			return;
		}
		//订单总金额
		Double amount = order.getDouble("amount");
		//根据用户所选择的支付方式不同作不同处理
		int payMethod = Integer.valueOf(flag);
		if (payMethod == OrderCode.OrderPayMethod.WEIXIN) {
			//，并转换为以“分”为单位
			String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
			//有效时间
			String startDate = DatetimeKit.getFormatDate(order.getDate("startDate"),"yyyyMMddHHmmss");
			String expireDate = DatetimeKit.getFormatDate(order.getDate("expireDate"),"yyyyMMddHHmmss");
			Map<String,String> params = new HashMap<String,String>();
	        params.put("appid", appid);
	        params.put("mch_id", mch_id);
	        params.put("body", "亿拼惠");
	        params.put("out_trade_no", orderNum); //订单编号
	        params.put("total_fee", amountStr); //订单金额  单位为分
	        params.put("spbill_create_ip", remoteip);  //终端ip
	        params.put("trade_type", "JSAPI"); //交易类型app：手机app支付，NATIVE：返回支付连接，可转成二维码客户扫描支付
	        params.put("nonce_str",  System.currentTimeMillis() / 1000 + ""); //随机字符串
	        params.put("notify_url", notify_url); //支付后通知回调地址
	        params.put("openid", openid);//用户OPENID
	        params.put("time_start", startDate);//用户OPENID
	        params.put("time_expire", expireDate);//用户OPENID
	        String sign = PaymentKit.createSign(params, paternerKey);    //生成签名
	        params.put("sign", sign);
	       
	        //下单
	        String xmlResult = PaymentApi.pushOrder(params);
	        System.out.println("下单后结果"+xmlResult);
	        Map<String,String> result = PaymentKit.xmlToMap(xmlResult);
	        
	        String return_code = result.get("return_code");
	        String return_msg = result.get("return_msg");
	        if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
	        	renderFailed(return_msg+"0");
	            return;
	        }
	        String result_code = result.get("result_code");
	        String err_code_des=result.get("err_code_des");
	        if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
	            renderFailed(err_code_des+"1");
	            return;
	        }
	      //更新订单支付方式为微信
			order.set("paytype", OrderCode.OrderPayMethod.WEIXIN).update();
	       //记录订单
	        new OrderPayAPIRecord().set("orderNum", orderNum)
	        .set("sendContent", params.toString())
			.set("returnContent", xmlResult)
			.set("payMethod", 1)
			.set("flag", 1)
			.save();
	     // 以下字段在return_code 和result_code都为SUCCESS的时候有返回
	        String prepay_id = result.get("prepay_id");
	        
	        String nonceStr = System.currentTimeMillis() + "";
	        String timestamp=DatetimeKit.getTimestamp();
	        Map<String, String> data = new HashMap<String, String>();
	        data.put("appId", appid);
	        data.put("timeStamp", timestamp);
	        data.put("nonceStr", nonceStr);
	        data.put("package", "prepay_id="+prepay_id);
	        data.put("signType", "MD5");
	        String appSign = PaymentKit.createSign(data, paternerKey);
	        data.put("sign", appSign);
	        renderSuccess(ResultMap.newInstance()
					.put("ORDERNUM",orderNum)
					.put("PACKAGE", "prepay_id="+prepay_id)
					.put("NONCESTR", nonceStr)
					.put("TIMESTAMP", timestamp)
					.put("SIGN", appSign));
			return;
		}else if (payMethod == OrderCode.OrderPayMethod.BALANCE1) {
			//更新订单支付方式为余额
			order.set("paytype", OrderCode.OrderPayMethod.BALANCE1).update();
			//查询用户余额  判断是否充足
			User user=getCurrentUser();
			if(user!=null){
	    		//查询成功
	    		//账户余额
				Double money = user.getDouble("money");
				if(Double.compare(money, amount)==-1){
					//余额不足
					renderFailed("余额不足");
					return;
				}
				//支付
				int count;
				try {
					count = service.chanegMoney(user,amount,orderNum,order);
					if(count==1){
			    		renderSuccess("支付成功");
			    		return;
			    	}else{
			    		//支付失败
			    		renderFailed("支付失败");
			    		return;
			    	}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					//支付失败
		    		renderFailed("支付失败");
		    		return;
				}
				
	    	}else{
	    		//查询余额失败
	    		logger.info(">>>>>>>>>>>>>>>查询用户余额失败");
	    		renderFailed("网络错误，请稍后重试");
	    		return;
	    	}
		}
		
	}
	/**
	 * 团购预支付APP端
	 * ORDERNUM  订单号
	 */
	public void pay2(){
		//获取订单支付方式
		String flag=getPara("FLAG");
		//获取订单号
		String orderNum = getPara("ORDERNUM");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else if("0".equals(flag)){
			renderFailed("请选择支付方式");
    		return;
		}
		
		//获取配置项
		//微信
		String appid =PropKit.get("APPWXPAY.appid");
		String mch_id =PropKit.get("MPWXPAY.mch_id");
		String paternerKey =PropKit.get("MPWXPAY.paternerkey");
		String notify_url =PropKit.get("MPWXPAY.goodsOrderNotifyUrl");
		//支付宝
		String gateway=PropKit.get("applipay.url");
		String app_id=PropKit.get("appalipay.partner");
		String privateKey=PropKit.get("appalipay.privateKey");
		String alipayPublicKey=PropKit.get("appalipay.alipayPublicKey");
		String charset=PropKit.get("applipay.charset");
		String sign_type=PropKit.get("applipay.signType");
		String app_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.appCertPublicKey");
		String alipay_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayCertPublicKey");
		String alipay_root_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayRootCert");
		String alipay_notify_url =PropKit.get("appalipay.goodsOrderNotifyUrl");
		//获取客户端IP
		String remoteip = EncryUtils.getRealIp(getRequest());
		if (StrKit.isBlank(remoteip)) {
			remoteip = "127.0.0.1";
        }
		//查询订单是否存在
		OrderG order = OrderG.me().findFirst("SELECT * FROM t_bus_order_gb WHERE orderNum = ? AND payState=? ", orderNum,OrderCode.OrderPayState.NO_PAY);
		if(order==null){
			renderFailed("订单不存在");
    		return;
		}
		//验证订单是否有效
		if(DatetimeKit.compareDate(order.getDate("expireDate")) == -1){
			renderFailed("您的订单已过期");
			return;
		}
		//验证团购是否过期
		Date date = order.getDate("gbendtime");
		if (DatetimeKit.compareDate(date)<0 || DatetimeKit.compareDate(date)==0 ) {
			renderFailed("团购已过期");
			return;
		}
		//订单总金额
		Double amount = order.getDouble("amount");
		//，并转换为以“分”为单位
		String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
		//获取订单总金额，并转换为以“元”为单位
		String amountStr1 = String.valueOf(Double.valueOf(amount));
		
		
		
		//根据用户所选择的支付方式不同作不同处理
		int payMethod = Integer.valueOf(flag);
		if (payMethod == OrderCode.OrderPayMethod.WEIXIN) {
			//有效时间
			String startDate = DatetimeKit.getFormatDate(order.getDate("startDate"),"yyyyMMddHHmmss");
			String expireDate = DatetimeKit.getFormatDate(order.getDate("expireDate"),"yyyyMMddHHmmss");
			///微信支付
			Map<String,String> params = new HashMap<String,String>();
	        params.put("appid", appid);
	        params.put("mch_id", mch_id);
	        params.put("body", "亿拼惠团购");
	        params.put("out_trade_no", orderNum); //订单编号
	        params.put("total_fee", amountStr); //订单金额  单位为分
	        params.put("spbill_create_ip", remoteip);  //终端ip
	        params.put("trade_type", "APP"); //交易类型app：手机app支付，NATIVE：返回支付连接，可转成二维码客户扫描支付
	        params.put("nonce_str",  System.currentTimeMillis() / 1000 + ""); //随机字符串
	        params.put("notify_url", notify_url); //支付后通知回调地址
	        params.put("time_start", startDate);//用户OPENID
	        params.put("time_expire", expireDate);//用户OPENID
	        String sign = PaymentKit.createSign(params, paternerKey);    //生成签名
	        params.put("sign", sign);
	       
	        //下单
	        String xmlResult = PaymentApi.pushOrder(params);
	        System.out.println("下单后结果"+xmlResult);
	        Map<String,String> result = PaymentKit.xmlToMap(xmlResult);
	        
	        String return_code = result.get("return_code");
	        String return_msg = result.get("return_msg");
	        if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
	        	renderFailed(return_msg+"0");
	            return;
	        }
	        String result_code = result.get("result_code");
	        String err_code_des=result.get("err_code_des");
	        if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
	            renderFailed(err_code_des+"1");
	            return;
	        }
	      //更新订单支付方式为微信
			order.set("paytype", OrderCode.OrderPayMethod.WEIXIN).update();
	       //记录订单
	        new OrderPayAPIRecord().set("orderNum", orderNum)
	        .set("sendContent", params.toString())
			.set("returnContent", xmlResult)
			.set("payMethod", 1)
			.set("flag", 1)
			.save();
	       
	     // 以下字段在return_code 和result_code都为SUCCESS的时候有返回
	        String prepay_id = result.get("prepay_id");
	        
	        String nonceStr = System.currentTimeMillis() + "";
	        String timestamp=DatetimeKit.getTimestamp();
	        Map<String, String> data = new HashMap<String, String>();
	        data.put("appid", appid);
	        data.put("partnerid", mch_id);
	        data.put("prepayid", prepay_id);
	        data.put("package", "Sign=WXPay");
	        data.put("noncestr", nonceStr);
	        data.put("timestamp", timestamp);
	        String appSign = PaymentKit.createSign(data, paternerKey);
	        data.put("sign", appSign);
	        String jsonStr = JsonUtils.toJson(data);
	        renderSuccess(ResultMap.newInstance().put("ORDERINFO", jsonStr).put("PROVIDER", "wxpay").put("ORDERNUM", orderNum).getAttrs());
			return;
			
		}else if(payMethod == OrderCode.OrderPayMethod.ALIPAY){
			///支付宝支付
			//构造client
			CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
			//设置网关地址
			certAlipayRequest.setServerUrl(gateway);
			//设置应用Id
			certAlipayRequest.setAppId(app_id);
			//设置应用私钥
			certAlipayRequest.setPrivateKey(privateKey);
			//设置请求格式，固定值json
			certAlipayRequest.setFormat("json");
			//设置字符集
			certAlipayRequest.setCharset(charset);
			//设置签名类型
			certAlipayRequest.setSignType(sign_type);
			//设置应用公钥证书路径
			certAlipayRequest.setCertPath(app_cert_path);
			//设置支付宝公钥证书路径
			certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
			//设置支付宝根证书路径
			certAlipayRequest.setRootCertPath(alipay_root_cert_path);
			//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
			AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
			model.setBody("亿拼惠团购");
			model.setSubject("亿拼惠");
			model.setOutTradeNo(orderNum);
			model.setTimeoutExpress("30m");
			model.setTotalAmount(amountStr1);
			model.setProductCode("QUICK_MSECURITY_PAY");
			//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
			AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
			request.setBizModel(model);
			request.setNotifyUrl(alipay_notify_url);
			try {
				//构造client
				AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
			        //这里和普通的接口调用不同，使用的是sdkExecute
			        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
			        System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
			      //记录订单
			        new OrderPayAPIRecord().set("orderNum", orderNum)
			        .set("sendContent", request.getBizModel().toString())
					.set("returnContent", response.getBody())
					.set("payMethod", 3)
					.set("flag", 1)
					.save();
			      //更新订单支付方式为支付宝
					order.set("paytype", OrderCode.OrderPayMethod.ALIPAY).update();
					//将结果返回给客户端
					renderSuccess(ResultMap.newInstance().put("ORDERINFO", response.getBody()).put("PROVIDER", "alipay").put("ORDERNUM", orderNum).getAttrs());
			    } catch (AlipayApiException e) {
			        e.printStackTrace();
			}
			
		}else if (payMethod == OrderCode.OrderPayMethod.BALANCE1) {
			//更新订单支付方式为余额
			order.set("paytype", OrderCode.OrderPayMethod.BALANCE1).update();
			//查询用户余额  判断是否充足
			User user=getCurrentUser();
			if(user!=null){
	    		//查询成功
	    		//账户余额
				Double money = user.getDouble("money");
				if(Double.compare(money, amount)==-1){
					//余额不足
					renderFailed("余额不足");
					return;
				}
				//支付
				int count;
				try {
					count = service.chanegMoney(user,amount,orderNum,order);
					if(count==1){
			    		renderSuccess("支付成功");
			    		return;
			    	}else{
			    		//支付失败
			    		renderFailed("支付失败");
			    		return;
			    	}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					//支付失败
		    		renderFailed("支付失败");
		    		return;
				}
				
	    	}else{
	    		//查询余额失败
	    		logger.info(">>>>>>>>>>>>>>>查询用户余额失败");
	    		renderFailed("网络错误，请稍后重试");
	    		return;
	    	}
		}
	}
	/**
	 * 团购预支付微信公众号支付<br/>
	 * 首先验证根据订单号查询订单记录是否存在，以此验证订单号是否正确<br/>
	 * @param ORDERNUM 要支付的订单号
	 * 
	 */
	public void pay3(){
		//获取订单支付方式
		String flag=getPara("FLAG");
		//获取OPENID
		String openid=getPara("OPENID");
		if(StrKit.isBlank(openid)){
			renderFailed("参数OPENID不能为空");
    		return;
		}
		//获取订单号
		String orderNum = getPara("ORDERNUM");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}
		//获取配置项
		String appid =PropKit.get("PWXPAY.appid");
		String mch_id =PropKit.get("PWXPAY.mch_id");
		String paternerKey =PropKit.get("PWXPAY.paternerkey");
		String notify_url =PropKit.get("PWXPAY.goodsOrderNotifyUrl");
		//获取客户端IP
		String remoteip = EncryUtils.getRealIp(getRequest());
		if (StrKit.isBlank(remoteip)) {
			remoteip = "127.0.0.1";
        }
		//查询订单是否存在
		OrderG order = OrderG.me().findFirst("SELECT * FROM t_bus_order_gb WHERE orderNum = ? AND payState=? ", orderNum,OrderCode.OrderPayState.NO_PAY);
				if(order==null){
					renderFailed("订单不存在");
		    		return;
				}
			//验证订单是否有效
			if(DatetimeKit.compareDate(order.getDate("expireDate")) == -1){
				renderFailed("您的订单已过期");
				return;
			}
			//验证团购是否过期
			Date date = order.getDate("gbendtime");
			if (DatetimeKit.compareDate(date)<0 || DatetimeKit.compareDate(date)==0 ) {
				renderFailed("团购已过期");
				return;
			}
			//订单总金额
			double amount = order.get("amount");
			//根据用户所选择的支付方式不同作不同处理
			int payMethod = Integer.valueOf(flag);
			if (payMethod == OrderCode.OrderPayMethod.WEIXIN) {
				//获取订单总金额，并转换为以“分”为单位
				String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
				//有效时间
				String startDate = DatetimeKit.getFormatDate(order.getDate("startDate"),"yyyyMMddHHmmss");
				String expireDate = DatetimeKit.getFormatDate(order.getDate("expireDate"),"yyyyMMddHHmmss");
				
				Map<String,String> params = new HashMap<String,String>();
		        params.put("appid", appid);
		        params.put("mch_id", mch_id);
		        params.put("body", "亿拼惠团购");
		        params.put("out_trade_no", orderNum); //订单编号
		        params.put("total_fee", amountStr); //订单金额  单位为分
		        params.put("spbill_create_ip", remoteip);  //终端ip
		        params.put("trade_type", "JSAPI"); //交易类型app：手机app支付，NATIVE：返回支付连接，可转成二维码客户扫描支付
		        params.put("nonce_str",  System.currentTimeMillis() / 1000 + ""); //随机字符串
		        params.put("notify_url", notify_url); //支付后通知回调地址
		        params.put("openid", openid);//用户OPENID
//		        params.put("time_start", startDate);//订单生效时间
//		        params.put("time_expire", expireDate);//订单失效时间
		        String sign = PaymentKit.createSign(params, paternerKey);    //生成签名
		        params.put("sign", sign);
		       
		        //下单
		        String xmlResult = PaymentApi.pushOrder(params);
		        System.out.println("公众号统一下单后结果"+xmlResult);
		        Map<String,String> result = PaymentKit.xmlToMap(xmlResult);
		        
		        String return_code = result.get("return_code");
		        String return_msg = result.get("return_msg");
		        if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
		        	renderFailed(return_msg+"0");
		            return;
		        }
		        String result_code = result.get("result_code");
		        String err_code_des=result.get("err_code_des");
		        if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
		            renderFailed(err_code_des+"1");
		            return;
		        }
		      //更新订单支付方式为微信
				order.set("paytype", OrderCode.OrderPayMethod.WEIXIN).update();
		       //记录订单
		        new OrderPayAPIRecord().set("orderNum", orderNum)
		        .set("sendContent", params.toString())
				.set("returnContent", xmlResult)
				.set("payMethod", 1)
				.set("flag", 1)
				.save();
		     // 以下字段在return_code 和result_code都为SUCCESS的时候有返回
		        String prepay_id = result.get("prepay_id");
		        
		        String nonceStr = System.currentTimeMillis() + "";
		        String timestamp=DatetimeKit.getTimestamp();
		        Map<String, String> data = new HashMap<String, String>();
		        data.put("appId", appid);
		        data.put("timeStamp", timestamp);
		        data.put("nonceStr", nonceStr);
		        data.put("package", "prepay_id="+prepay_id);
		        data.put("signType", "MD5");
		        String appSign = PaymentKit.createSign(data, paternerKey);
		        data.put("sign", appSign);
		        renderSuccess(ResultMap.newInstance()
						.put("ORDERNUM",orderNum)
						.put("PACKAGE", "prepay_id="+prepay_id)
						.put("NONCESTR", nonceStr)
						.put("TIMESTAMP", timestamp)
						.put("APPID", appid)
						.put("SIGN", appSign));
				return;
			}else if (payMethod == OrderCode.OrderPayMethod.BALANCE1) {
				//更新订单支付方式为余额
				order.set("paytype", OrderCode.OrderPayMethod.BALANCE1).update();
				//查询用户余额  判断是否充足
				User user=getCurrentUser();
				if(user!=null){
		    		//查询成功
		    		//账户余额
					Double money = user.getDouble("money");
					if(Double.compare(money, amount)==-1){
						//余额不足
						renderFailed("余额不足");
						return;
					}
					//支付
					int count;
					try {
						count = service.chanegMoney(user,amount,orderNum,order);
						if(count==1){
				    		renderSuccess("支付成功");
				    		return;
				    	}else{
				    		//支付失败
				    		renderFailed("支付失败");
				    		return;
				    	}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						//支付失败
			    		renderFailed("支付失败");
			    		return;
					}
					
		    	}else{
		    		//查询余额失败
		    		logger.info(">>>>>>>>>>>>>>>查询用户余额失败");
		    		renderFailed("网络错误，请稍后重试");
		    		return;
		    	}
			}
			
	}
	/**
	 * @param ORDERNUM 订单号
	 * @param TOKENP 支付token
	 */
	public void query(){
		String orderNum = getPara("ORDERNUM");
		String token = getPara("TOKENP");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else if(StrKit.isBlank(token)){
			renderFailed("参数TOKENP不能为空");
    		return;
		}
		try {
			int count = service.query(getCurrentUser(),orderNum,token);
			if(count == 1){
				renderSuccess(ResultMap.newInstance().put("PAYSTATE", count).getAttrs());
			}else{
				renderFailed("2");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			String split = e.getMessage().split(":")[1];
			renderFailed(split);
		}
	}
	
	/**
	 * 查询团队列表
	 * 
	 */
	@Clear(AuthLoginInterceptor.class)
	public void teamList(){
		//查找团队数
		String id = getPara("ID");
		String inviteid = getPara("USERID");
		if(StrKit.isBlank(id)){
			renderFailed("参数ID不能为空");
    		return;
		}else if(StrKit.isBlank(inviteid)){
			renderFailed("参数USERID不能为空");
    		return;
		}
		//显示个数
		int nums = 0;
		try {
			nums = (int)SysConfig.getGroupSize();
		} catch (Exception e) {
		}
		//筛选出未免单、团购人数未满的  团中团列表
		List<Record> list = service.teamList(id,inviteid);
		System.out.println(">>>>>>>>>>"+list.size());
		if(list!=null && list.size()>0){
			if(list.size()>=nums){
				list = list.subList(0, nums);
			}
			
//			for(Record re : list){
//				List<Record> num = service.teamNum(re.getStr("teamNum"),id);
//				if(num!=null && num.size()>0){
//					re.set("list", num);
//				}
//			}
			renderSuccess(list);
			return;
		}
		renderFailed();
	}

	/**
	 * 查询团队列表
	 * 
	 */
	public void teamListLogin(){
		//查找团队数
		String id = getPara("ID");
		String inviteid = getPara("USERID");
		if(StrKit.isBlank(id)){
			renderFailed("参数ID不能为空");
    		return;
		}else if(StrKit.isBlank(inviteid)){
			renderFailed("参数USERID不能为空");
    		return;
		}
		if(getCurrentUser().getInt("id")==Integer.parseInt(inviteid)){
			inviteid = "0";
		}
		//显示个数
		int nums = 0;
		try {
			nums = (int)SysConfig.getGroupSize();
		} catch (Exception e) {
		}
		//筛选出未免单、团购人数未满的  团中团列表
		List<Record> list = service.teamList(id,inviteid);
		System.out.println(">>>>>>>>>>"+list.size());
		if(list!=null && list.size()>0){
			if(list.size()>=nums){
				list = list.subList(0, nums);
			}
			
//			for(Record re : list){
//				List<Record> num = service.teamNum(re.getStr("teamNum"),id);
//				if(num!=null && num.size()>0){
//					re.set("list", num);
//				}
//			}
			renderSuccess(list);
		} else {
			renderSuccess();
		}
		
	}
	
	
	
	/**
	 * 查询所有的团购商品
	 */
	@Clear(AuthLoginInterceptor.class)
	public void findGroupBuyGoods() {
		List<Record> groupBuyGoodsList=service.findGroupBuyGoods();
		if (groupBuyGoodsList!=null&&groupBuyGoodsList.size()>0) {
			renderSuccess(groupBuyGoodsList);
		}else{
			renderFailed("网络繁忙...，请稍后重试");
		}
	}
	
	/**
	 * 查询所有的团购商品
	 * @param ORDERBY 排序，1：默认排序，2：销量从高到低，3：价格从低到高，4：价格从高到低，V1.3.1以后用
	 * @param PAGENUM 页码
	 * @param PAGESIZE 数量
	 */
	@Clear(AuthLoginInterceptor.class)
	public void findGroupBuyGoodsPage() {
		int pageNum = getParaToInt("PAGENUM",1);
		int pageSize = getParaToInt("PAGESIZE",PropKit.getInt("constants.pageSize"));
		Page<Record> page = null;
		page=service.findGroupBuyGoodsPage(pageNum,pageSize);
		if (page.getPageSize()>0) {
			renderSuccess(ResultMap.newInstance()
					.put("PAGENUMBER", page.getPageNumber())
					.put("PAGESIZE", page.getPageSize())
					.put("TOTALPAGE", page.getTotalPage())
					.put("TOTALROW", page.getTotalRow())
					.put("LIST", page.getList()));
		}else{
			renderFailed("网络繁忙...，请稍后重试");
		}
	}
	
	/**
	 * 发起邀请成团
	 */
	public void beTeam(){
		int orderid = getParaToInt("ORDERID",0);
		if ( orderid==0 ){
			renderFailed("请录入商品ID");
    		return;
		}
		service.beTeam(orderid,getCurrentUser());
		renderSuccess();
	}
	
	
}
